package com.hm.service.impl.auth;

import com.hm.service.framework.base.BaseServiceImpl;
import com.hm.service.service.main.RequestLockService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;


@Service
public class RequestLockServiceImpl extends BaseServiceImpl implements RequestLockService {

    private static final Logger logger = LoggerFactory.getLogger(RequestLockServiceImpl.class);

    @Qualifier("JedisPool")
    private final JedisPool jedisPool;

    @Autowired
    @Qualifier("RequestLockMap")
    public HashMap<String, String> requestLockMap;

    public RequestLockServiceImpl(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    @Override
    public HashMap<String, String> verifierLock(HashMap<String, String> params) {
        HashMap<String, String> resMap = new HashMap<>();
        String sessionId = params.get("sessionId");
        String serveName = params.get("serveName");
        if (!"3".equals(requestLockMap.get(serveName))) {
            resMap.put("state", "000");
            resMap.put("msg", "接口不是锁目标");
            return resMap;
        }
        //根据接口和session生成唯一key
        String key = serveName + "-" + sessionId;
        try (Jedis jedis = jedisPool.getResource()) { //try块退出时，会自动调用res.close()方法，关闭资源。
            boolean exists = jedis.exists(key);
            if (exists) {
                //说明有缓存-锁生效
                resMap.put("state", "001");
                resMap.put("msg", "请求太频繁，请稍后再试~");
            } else {
                //说明没缓存
                resMap.put("state", "000");
                resMap.put("msg", "已设置接口锁");
                //设置锁时间为2秒
                jedis.setex(key, 2, "lock");
            }
        }
        return resMap;
    }
}
